//
//  HomeFansLivingViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/12.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HomeFansLivingViewController.h"
#import "WatchViewController.h"
#import "LiveListModel.h"
#import "StarLivingListCell.h"
#import "WatchLiveTipView.h"
#import "BuyViewController.h"
#import "FlowLayout.h"

@interface HomeFansLivingViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,WatchLiveTipViewDelegate>
{
    NSMutableArray *_livelistArr;
    int _page;
    BOOL _isFirstCome; //第一次加载帖子时候不需要传入此关键字，当需要加载下一页时：需要传入加载上一页时返回值字段“maxtime”中的内容。
    int _totalPage;//总页数
    BOOL _isLoad;//是否正在下拉刷新或者上拉加载。default NO。
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) FlowLayout *flowLayout;
@property (nonatomic, strong) WatchLiveTipView *watchTipView;
@property (nonatomic, strong) UIView *coverView;
/**
   判断余额是否充足 YES:充足 NO:不足
 */
@property (nonatomic, assign) BOOL BalanceTag;
@end

@implementation HomeFansLivingViewController
static NSString *StarLivingListCellID = @"StarLivingListCellID";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.collectionView.mj_header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self StarlistRequest];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    _livelistArr = [NSMutableArray arrayWithCapacity:1];
}

#pragma mark -- 明星直播列表请求
- (void)StarlistRequest {
    NSDictionary *dic = @{
                          @"udid":User_ID,
                          @"token":TOKEN,
                          @"page":@"0",
//                          @"amount":@"1",
                          };
    NSString *urlString = [TEST_URL stringByAppendingString:kLiveList];
    [NetworkTools postReqeustWithParams:dic UrlString:urlString successBlock:^(id responseObject) {
        [self endRefresh];
        _totalPage = ceilf([responseObject[@"data"][@"num"] floatValue]/20);
        if (_livelistArr.count>0) {
            [_livelistArr removeAllObjects];
        }
        NSArray *array = responseObject[@"data"][@"list"];
        for (NSDictionary *dict in array) {
            LiveListModel *model = [[LiveListModel alloc] initWithDict:dict];
            [_livelistArr addObject:model];
        }
//        self.flowLayout.array = [NSArray arrayWithArray:_livelistArr];
        [self.flowLayout invalidateLayout];
        [self.collectionView reloadData];
    } failureBlock:^(NSError *error) {
        [self endRefresh];
    } showHUD:NO];
}


#pragma mark -- 支付观看看直播费用
- (void)payLiveWithChannel:(NSString *)channel Price:(NSString *)price ChatRoomid:(NSString *)chatroomid S_uid:(NSString *)s_uid {
    NSDictionary *paramDic = @{
                               @"udid":User_ID,
                               @"token":TOKEN,
                               @"channel":channel,
                               @"price":price
                               };
    NSString *urlString = [TEST_URL stringByAppendingString:kPayLive];
    [NetworkTools postReqeustWithParams:paramDic UrlString:urlString successBlock:^(id responseObject) {
        [self PulladdressRequestWithRoomId:channel ChatRoomid:chatroomid S_uid:s_uid];
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}


#pragma mark -- 查询账户余额接口
- (void)BalanceRequestWithLiveListModel:(LiveListModel *)listModel {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kBalance];
    [self showHUDInView:self.view title:nil];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        NSString *balance = responseObject[@"data"][@"u_balance"];
        if ([balance intValue] < [listModel.s_price intValue]) {//余额不足
            self.BalanceTag = NO;
        } else {//余额充足
            self.BalanceTag = YES;
        }
        [self creatWatchTipViewWith:self.BalanceTag LiveListModel:listModel];
    } failureBlock:^(NSError *error) {
      [self hideHUD];
    } showHUD:NO];
}

#pragma mark -- 获取观看直播地址
- (void)PulladdressRequestWithRoomId:(NSString *)roomid ChatRoomid:(NSString *)chatroomid S_uid:(NSString *)s_uid {
    NSDictionary *dic = @{
                          @"udid":User_ID,
                          @"token":TOKEN,
                          @"channel":roomid,
                          @"group":chatroomid,
                          @"status":@"1" //1表示进入直播间
                          };
    NSString *urlString = [TEST_URL stringByAppendingString:kWatchlive];
    [NetworkTools postReqeustWithParams:dic UrlString:urlString successBlock:^(id responseObject) {
        
        NSString *pullUrl = responseObject[@"data"][@"url"][1];
        
        WatchViewController *watchVc = [[WatchViewController alloc] init];
        watchVc.roomid = roomid;
        watchVc.chatroomid = chatroomid;
        watchVc.s_uid = s_uid;
        watchVc.pullUrl = pullUrl;
        [self presentViewController:watchVc animated:YES completion:nil];

    } failureBlock:^(NSError *error) {
       
    } showHUD:NO];
}

/**
 *  停止刷新
 */
-(void)endRefresh{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        self.flowLayout = [[FlowLayout alloc] init];
        [self.flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT - kNAV_HEIGHT - 40) collectionViewLayout:self.flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        __weak typeof(self) weakSelf = self;
        //默认block方法：设置下拉刷新
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _page = 0;
            [weakSelf StarlistRequest];
        }];
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _page++;
            if (_page == _totalPage + 1) {
                self.collectionView.mj_footer.state = MJRefreshStateNoMoreData;
            } else {
                [weakSelf StarlistRequest];
            }
        }];
        [_collectionView registerNib:[UINib nibWithNibName:@"StarLivingListCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:StarLivingListCellID];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}


#pragma mark -- UICollectionView Delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _livelistArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    StarLivingListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:StarLivingListCellID forIndexPath:indexPath];
//    cell.livelistModel = [_livelistArr objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        cell.starName.text = @"高圆圆";
        cell.audiences.text = @"3万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_1"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 1) {
        cell.starName.text = @"韩雪";
        cell.audiences.text = @"2万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_2"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 2) {
        cell.starName.text = @"蒋欣";
        cell.audiences.text = @"2.98万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_3"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    }
    else if (indexPath.row == 3) {
        cell.starName.text = @"李晨";
        cell.audiences.text = @"2.98万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_4"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 4) {
        cell.starName.text = @"李易峰";
        cell.audiences.text = @"3000万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_5"];
        cell.paperTip.hidden = NO;
        cell.paperTipText.hidden = NO;
        cell.presentTip.hidden = NO;
        cell.presentTipText.hidden = NO;
    } else if (indexPath.row == 5) {
        cell.starName.text = @"刘涛";
        cell.audiences.text = @"8万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_6"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 6) {
        
        cell.starName.text = @"孙俪";
        cell.audiences.text = @"3.9万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_7"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 7) {
        
        cell.starName.text = @"佟丽娅";
        cell.audiences.text = @"1万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_8"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 8) {
        
        cell.starName.text = @"王凯";
        cell.audiences.text = @"3.3万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_9"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 9) {
        
        cell.starName.text = @"吴磊";
        cell.audiences.text = @"3.3万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_10"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 10) {
        
        cell.starName.text = @"杨颖";
        cell.audiences.text = @"3.3万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_11"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 11) {
        
        cell.starName.text = @"赵丽颖";
        cell.audiences.text = @"3.3万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_12"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    } else if (indexPath.row == 12) {
    
        cell.starName.text = @"郑爽";
        cell.audiences.text = @"3.3万人";
        cell.bkImage.image = [UIImage imageNamed:@"cover_13"];
        cell.paperTip.hidden = YES;
        cell.paperTipText.hidden = YES;
        cell.presentTip.hidden = YES;
        cell.presentTipText.hidden = YES;
    }
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LiveListModel *listModel = _livelistArr[indexPath.row];
    //查询账户余额 
    [self BalanceRequestWithLiveListModel:listModel];

}

//定义每个Item 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((kSCREEN_WIDTH - 20)/2,(kSCREEN_WIDTH - 20)/2 + 40);
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

#pragma mark -- watchTipView 
- (void)creatWatchTipViewWith:(BOOL)BalanceTag LiveListModel:(LiveListModel*)listModel {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.watchTipView = [[NSBundle mainBundle] loadNibNamed:@"WatchLiveTipView" owner:self options:nil].lastObject;
    self.watchTipView.delegate = self;
    self.watchTipView.livelistModel = listModel;
    [window addSubview:self.watchTipView];
    self.watchTipView.backgroundColor = kRGB(1, 1, 1, 0.6);
    [self.watchTipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(window);
    }];
    
    //设置余额不足的隐藏
    if (self.BalanceTag == YES) {
        self.watchTipView.NoPayNotice.hidden = YES;
        [self.watchTipView.watchBtn setTitle:@"观看直播" forState:UIControlStateNormal];
    } else {
        self.watchTipView.NoPayNotice.hidden = NO;
        [self.watchTipView.watchBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    }
}

#pragma mark -- WatchTipViewDelegate

- (void)closeTipView {
    [self.watchTipView removeFromSuperview];
}

- (void)buyClickWithTipView:(WatchLiveTipView *)watchtipView LiveListModel:(LiveListModel*)liveListModel {
    if (self.BalanceTag == NO) {//去购买芝麻
        [self.watchTipView removeFromSuperview];
        BuyViewController *buyVC = [[BuyViewController alloc] init];
        buyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:buyVC animated:YES];
    } else {//观看直播
        [self.watchTipView removeFromSuperview];
        [self payLiveWithChannel:liveListModel.l_channel Price:liveListModel.s_price ChatRoomid:liveListModel.l_group S_uid:liveListModel.l_udid];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
